<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author FIRE
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'pay:pmPayrequest:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="40%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_PmPayRequest"
        completeText="提交"
        :loading="loadingRef"
        :auth="'pay:pmPayrequest:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsPayPmPayrequestForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { PmPayrequest, pmPayrequestresultSave, pmPayrequestForm } from '/@/api/pay/pmPayrequest';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('pay.pmPayrequest');
  const { showMessage } = useMessage();
  const record = ref<PmPayrequest>({} as PmPayrequest);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('结算确认'),
  }));

  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('申请信息'),
      // field: 'employeeInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    // {
    //   label: t('单据编号'),
    //   field: 'djno',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    //   show:false
    // },
    {
      label: t('项目名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      dynamicDisabled: true,
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
      },
      itemProps: { validateTrigger: 'blur' },
    },
    {
      label: t('项目编号'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
    },

    {
      label: t('款项类型'),
      field: 'payType',
      component: 'Select',
      dynamicDisabled: true,
      componentProps: {
        dictType: 'zf_pay_type',
        allowClear: true,
      },
    },
    {
      label: t('申请金额'),
      field: 'imoney',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      dynamicDisabled: true,
      // rules: [{ required: true }, { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('申请说明'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
    },

    {
      label: t('申请时间'),
      field: 'createDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
    },
    {
      label: t('申请图片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmPayRequestCreate_image',
        uploadType: 'image',
      },
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
      // rules: [
      //   { required: true },
      //   {
      //     validator(_rule, value) {
      //       return new Promise((resolve, reject) => {
      //         const len = !value || value['PmPayRequestCreate_image__len'] || 0;
      //         if (len == 0) reject(t('请上传图片'));
      //         else resolve();
      //       });
      //     },
      //   },
      // ],
    },
    /* {
      label: t('核价信息'),
      // field: 'employeeInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: computed(() => (record.value.payType == '222' ? true : false)),
    },
    {
      label: t('核价金额'),
      field: 'accountMoney',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      ifShow: computed(() => (record.value.payType == '222' ? true : false)),
      dynamicDisabled: true,
      // rules: [{ required: true }, { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('结算资料附件'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmPayRequestAccount_file',
        uploadType: 'file',
      },
      ifShow: computed(() => (record.value.payType == '222' ? true : false)),
      dynamicDisabled: true,
      colProps: { lg: 24, md: 24 },
      // rules: [
      //   { required: true },
      //   {
      //     validator(_rule, value) {
      //       return new Promise((resolve, reject) => {
      //         const len = !value || value['PmPayRequestAccount_file__len'] || 0;
      //         if (len == 0) reject(t('请上传图片'));
      //         else resolve();
      //       });
      //     },
      //   },
      // ],
    },
    {
      label: t('结算信息'),
      // field: 'employeeInfo',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('实际金额'),
      field: 'realMoney',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      rules: [
        { required: true },
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('支付图片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmPayRequestResult_image',
        uploadType: 'image',
      },
      colProps: { lg: 24, md: 24 },
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['PmPayRequestResult_image__len'] || 0;
              if (len == 0) reject(t('请上传图片'));
              else resolve();
            });
          },
        },
      ],
    }, */
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmPayrequestForm(data);
    record.value = (res.pmPayrequest || {}) as PmPayrequest;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    // updateSchema([
    //   {
    //     field: 'djno',
    //     componentProps: {
    //       disabled: !record.value.isNewRecord,
    //     },
    //   },
    // ]);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      // console.log('submit', params, data, record);
      const res = await pmPayrequestresultSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
